package com.yitiao.socket.chatroom.demo;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;

public class ClientHandler implements CompletionHandler<Integer, Object> {
    private AsynchronousSocketChannel clientChannel;

    public ClientHandler(AsynchronousSocketChannel channel) {
        this.clientChannel = channel;
    }

    @Override
    public void completed(Integer result, Object attachment) {
        Map<String, Object> info = (Map<String, Object>) attachment;
        String type = (String) info.get("type");

        if (type.equals("read")){
            ByteBuffer buffer = (ByteBuffer) info.get("buffer");
            buffer.flip();
            info.put("type", "write");
            clientChannel.write(buffer, info, this);
            buffer.clear();
        }else {
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            info.put("type", "read");
            info.put("buffer", buffer);

            clientChannel.read(buffer, info, this);
        }


    }

    @Override
    public void failed(Throwable exc, Object attachment) {

    }
}
